//
//  YWLittleVideoPlayerView.m
//  YueshengToutiao
//
//  Created by yellow on 2021/4/21.
//  Copyright © 2021 YW. All rights reserved.
//

#import "YWLittleVideoPlayerView.h"
#import "YWGetNewsDataStatus.h"
#import <TXLiteAVSDK_Player/TXLiteAVSDK.h>


@interface YWLittleVideoPlayerView ()

@property (weak, nonatomic) IBOutlet UIView *functionView;
@property (weak, nonatomic) IBOutlet UILabel *detailLabel;
@property (weak, nonatomic) IBOutlet UIButton *authorBtn;
@property (weak, nonatomic) IBOutlet UIButton *likeBtn;
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;
- (IBAction)authorBtnClick:(UIButton *)sender;
- (IBAction)likeBtnClick:(UIButton *)sender;
- (IBAction)shareBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *playOrPauseBtn;

@property (weak, nonatomic) IBOutlet UIView *videoBgView;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UIButton *loadingView;

@property (weak, nonatomic) IBOutlet UIView *progressBgView;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
- (IBAction)sliderValueChange;
- (IBAction)touchDownSlider;
- (IBAction)touchUpInsideSlider;

@property (weak, nonatomic) IBOutlet UIView *grayView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottomConstraint;
@property (weak, nonatomic) IBOutlet YWConcernBtn *concernBtn;
- (IBAction)concernBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *authorBtnBottomConstraint;
@property (weak, nonatomic) IBOutlet UIView *videoView;

@property (nonatomic, assign) BOOL mute;

@property(nonatomic,copy)NSString *urlString;

//播放器是否正在播放 （这个是暂停播放也算是YES的\暂停播放也叫正在播放）
@property (nonatomic, assign) BOOL isPlaying_containPause;


@end

@implementation YWLittleVideoPlayerView

-(BOOL)isPlaying_containPause{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
  
    if (playerManager.currentVideoMessageModel.player != nil) {
        return YES;
    }
    else{
        return NO;
        
    }
}


+(instancetype)littleVideoPlayerView{
    
    return [[NSBundle mainBundle] loadNibNamed:@"YWLittleVideoPlayerView" owner:nil options:nil].lastObject;

}

-(void)awakeFromNib{
    [super awakeFromNib];
    
    
    //单击手势暂停播放
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self addGestureRecognizer:tap];
    
    UITapGestureRecognizer *doubleLikeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleLikeTap:)];
    
    doubleLikeTap.numberOfTapsRequired = 2;
    
    [self addGestureRecognizer:doubleLikeTap];
    
    // 关键在这一行，双击手势确定监测失败才会触发单击手势的相应操作
    [tap requireGestureRecognizerToFail:doubleLikeTap];
    
    
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground) name:YWEnterBackgroundNote object:nil];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)enterBackground{
    
    [self pausePlay];
    self.playOrPauseBtn.selected = NO;
    
}

-(void)setupUI{
    
    self.backgroundColor = [UIColor blackColor];
    
    if (isIphoneX) {
        self.authorBtnBottomConstraint.constant = 15+25;
    }
    else{
        
        self.authorBtnBottomConstraint.constant = 15;
    }
    
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
       gradientLayer.colors = @[(__bridge id)YWColorRGBA(0, 0, 0, 0.8).CGColor, (__bridge id)[UIColor clearColor].CGColor];
//       gradientLayer.locations = @[@0, @1.0];
       gradientLayer.startPoint = CGPointMake(0, 1.0);
       gradientLayer.endPoint = CGPointMake(0, 0);
       gradientLayer.frame = CGRectMake(0, 0, Wi, self.grayView.height);
       [self.grayView.layer addSublayer:gradientLayer];
    
    
    self.authorBtn.layer.cornerRadius = 20;
    self.authorBtn.clipsToBounds = YES;
    
    //loadingView的旋转动画一直存在就行、不用考虑显示隐藏、所以写在了awakeFromNib
    //添加loading动画
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 0.9;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.removedOnCompletion = NO;//这个属性才会重新出现界面时不会停止动画
    [self.loadingView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
    //简单点、不要loadingView了
    self.loadingView.hidden = YES;
    
    // 设置进度条的内容
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"进度条原点3"] forState:UIControlStateNormal];
    [self.progressSlider setMaximumTrackImage:[UIImage imageNamed:@"MaximumTrackImage"] forState:UIControlStateNormal];
    [self.progressSlider setMinimumTrackImage:[UIImage imageNamed:@"MinimumTrackImage"] forState:UIControlStateNormal];
    
    
    // 2、设置按钮的状态
    self.playOrPauseBtn.hidden = YES;
    
    // 3、设置slider
    self.progressSlider.value = 0;
    
    // 4、设置两个时间label
    self.currentTimeLabel.text = @"00:00";
    
    self.totalTimeLabel.text = @"00:00";
    
}


////////////////////////////////////////////////////////////
//刚出来的时候
-(void)setStatus:(YWGetNewsDataStatus *)status{
    _status = status;
    
    //iconView是一直显示、刚出来就会见到
    if ([status.Img isKindOfClass:[NSNull class]] || status.Img == nil) {
        status.Img = @"";
    }
    [self.iconView sd_setImageWithURL:[NSURL URLWithString:status.Img] placeholderImage:[UIImage imageWithColor:[UIColor blackColor]]];
    
    if ([status.AuthorImg isKindOfClass:[NSNull class]] || status.AuthorImg == nil) {
        status.AuthorImg = @"";
    }
    
    [self.authorBtn sd_setImageWithURL:[NSURL URLWithString:status.AuthorImg] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"头像3"]];
    
    
    self.nameLabel.text = status.Author;
    
    NSString *detailString = status.Describe;
    
    if ([detailString isKindOfClass:[NSNull class]]||detailString == nil) {
        detailString = @"";
    }
    
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:6];
    
        NSMutableAttributedString * attributedStringTitle = [[NSMutableAttributedString alloc] initWithString:detailString];
           [attributedStringTitle addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [detailString length])];
       [self.detailLabel setAttributedText:attributedStringTitle];
    
//    self.likeBtn.selected = status.IsLike.boolValue;
    
    
    
    if (status.IsLike.integerValue == 1) {
        
        self.likeBtn.selected = YES;
        
        [self.likeBtn setTitle:[NSString stringWithFormat:@"%@",status.Praise] forState:UIControlStateNormal];
    }
    else{
        
        self.likeBtn.selected = NO;
        
        [self.likeBtn setTitle:[NSString stringWithFormat:@"点赞"] forState:UIControlStateNormal];
    }
    
    //老师的是否关注还没有
    if (status.IsFocus.intValue == 1) {
        self.concernBtn.isSelect = YES;
    }
    else{
        self.concernBtn.isSelect = NO;
    }
    
}

#pragma mark - 预加载后播放开始播放暂停播放继续播放停止播放





//开始
-(void)startPlayWithUrl:(NSString *)urlString withMute:(BOOL)mute{
    
    
    self.progressBgView.hidden = YES;
    
    self.playOrPauseBtn.hidden = YES;
    
    
    self.urlString = urlString;
    
    MJWeakSelf
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
  
      [playerManager startPlayWithUrl:urlString view:self.videoView complication:^{
          
          //重设是否要静音
//          weakSelf.mute = weakSelf.mute;
          
          //这里用在朋友圈列表、默认就是静音
          //是否静音这里应该是YES
          
          //因为列表VC和小视频详情VC都共用这个videoView、所以mute由外界提供
          weakSelf.mute = mute;
          
          if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidStartPlay:)]) {
              [weakSelf.delegate videoViewDidStartPlay:weakSelf];
          }
  
      } startPlay:^{
          
          weakSelf.loadingView.hidden = YES;
          
         
      } progress:^(float progress, float duration, float playable) {
  
          weakSelf.loadingView.hidden = YES;
//          if (weakSelf.isPlaying) {
              weakSelf.playOrPauseBtn.hidden = YES;
//          }
//          else{
//
//              weakSelf.playOrPauseBtn.hidden = NO;
//
//          }
          
          weakSelf.progressSlider.value = progress / duration;
          
          weakSelf.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:duration];
          
          weakSelf.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:progress];
          
          
      } end:^{
  
      } loading:^{
          //这个不要了因为不好看
          //        weakSelf.loadingView.hidden = NO;
          
      }];
    
}

//去其它view继续播放，不要先停止之前正在播放的
-(void)continuePlayWithAnthorViewWithUrl:(NSString *)urlString WithMute:(BOOL)mute{
    
    self.progressBgView.hidden = YES;
    
    self.playOrPauseBtn.hidden = YES;
    
    self.urlString = urlString;
    
    MJWeakSelf
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    //继续播放
    [self continuePlay];

    [playerManager continuePlayWithAnthorView:self.videoView complication:^{
        
        weakSelf.mute = mute;
        
        if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidStartPlay:)]) {
            [weakSelf.delegate videoViewDidStartPlay:weakSelf];
        }
        
    } startPlay:^{
        
        weakSelf.loadingView.hidden = YES;
       
    } progress:^(float progress, float duration, float playable) {
        weakSelf.loadingView.hidden = YES;
//        if (weakSelf.isPlaying) {
            weakSelf.playOrPauseBtn.hidden = YES;
//        }
//        else{
//
//            weakSelf.playOrPauseBtn.hidden = NO;
//
//        }
        
        weakSelf.progressSlider.value = progress / duration;
        
        weakSelf.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:duration];
        
        weakSelf.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:progress];
        
    } end:^{
        
    } loading:^{
        //这个不要了因为不好看
//        weakSelf.loadingView.hidden = NO;
    }];
    
  
    
}


//暂停
-(void)pausePlay{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager pausePlayWithComplication:^{
        
    }];
    
    self.progressBgView.hidden = NO;
    self.playOrPauseBtn.hidden = NO;

}


//继续
-(void)continuePlay{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager continuePlayWithComplication:^{
        
    }];
    
    self.progressBgView.hidden = YES;
    self.playOrPauseBtn.hidden = YES;
}


//暂停
-(void)stopPlay{
    
    MJWeakSelf
 
        YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
        [playerManager stopPlayWithComplication:^{
            if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidSotpPlay:)]) {
                [weakSelf.delegate videoViewDidSotpPlay:weakSelf];
            }
        }];
    
    self.progressBgView.hidden = NO;
    self.playOrPauseBtn.hidden = NO;
}


-(void)setMute:(BOOL)mute{
    _mute = mute;
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    [playerManager setMute:mute];
    
}


-(BOOL)isPlaying{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    return playerManager.currentVideoMessageModel.isPlaying;
}


- (void)snapshot:(void (^)(UIImage *))snapshotCompletionBlock{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    [playerManager snapshot:^(UIImage * _Nonnull image) {
        if (snapshotCompletionBlock) {
            snapshotCompletionBlock(image);
        }
    }];
    
}



////////////////////////////////////////////////////////////

#pragma mark - 一些functionView方法
//暂停播放
- (void)tapAction:(UITapGestureRecognizer *)sender {
    
    self.playOrPauseBtn.hidden = !self.playOrPauseBtn.hidden;
    
    if ( self.playOrPauseBtn.hidden) {
        [self continuePlay];
    }
    else{
        [self pausePlay];
    }
    
}


- (IBAction)sliderValueChange{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    // 更新时间label数据
    NSTimeInterval currentTime = playerManager.currentVideoMessageModel.totalTime * self.progressSlider.value;
    
    NSTimeInterval totalTime = playerManager.currentVideoMessageModel.totalTime;
    
    
    self.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:currentTime];
    
    self.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:totalTime];
    
    // 更新视频进度
    [playerManager seekToTime:currentTime];
  
    
}

- (IBAction)touchDownSlider{

    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager pausePlayWithComplication:^{
       
    }];

}
- (IBAction)touchUpInsideSlider{
    [self continuePlay];

}







- (void)doubleLikeTap:(UITapGestureRecognizer *)sender {
    
}


- (IBAction)shareBtnClick:(UIButton *)sender {
    
}



- (IBAction)likeBtnClick:(UIButton *)sender {


}



- (IBAction)concernBtnClick:(UIButton *)sender {
  
    
}


- (IBAction)authorBtnClick:(UIButton *)sender {
    
    
}


@end
